﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Daco.Security;
using Daco.Web.Store;

namespace Daco.Web.Pages.Secure
{
    public enum EAction
    {
        View = 1,
        Add = 2,
        Update = 4,
        Delete = 8
    }

    public partial class AddEditProduct : Daco.Web.UI.SitePage
    {
        private EAction _action = EAction.Add;
        private CProduct _product = null;

        public AddEditProduct()
            : base("EStore", "AddEditProduct", new CPermission(EPermission.InsertAccesss | EPermission.UpdateAccess | EPermission.SelectAccess))
        {
            this.Init += new EventHandler(AddEditProduct_Init);
            this.Load += new EventHandler(AddEditProduct_Load);
            this.PreRender += new EventHandler(AddEditProduct_PreRender);
        }

        void AddEditProduct_Init(object sender, EventArgs e)
        {
            fckDescription.BasePath = Page.ResolveUrl("~/FCKEditor/");
        }

        void AddEditProduct_Load(object sender, EventArgs e)
        {
            try
            {
                _action = (EAction)Enum.Parse(typeof(EAction), Request.QueryString["act"], true);
            }
            catch
            {
                _action = EAction.Add;
            }

            if (_action == EAction.Add)
            {
                _product = new CProduct();
            }
            else if (_action == EAction.Update)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["pid"]) && (_product = CProduct.GetProduct(Request.QueryString["pid"])) != null)
                {
                    List<CProductDescription> descriptions = _product.GetDescriptions();
                    if (descriptions.Count > 0)
                    {
                        fckDescription.Value = _product.GetDescription(descriptions[0].DescriptionID).Body;
                    }
                }
            }

            if (!Page.IsCallback && !Page.IsPostBack)
            {
                BindCategoryList();
                BindManufactureList();
                BindUnitMeasureList();
                BindForm();
            }
        }

        void AddEditProduct_PreRender(object sender, EventArgs e)
        {
            if (_action == EAction.Add)
            {
                lbAction.Text = "Thêm mới sản phẩm";
            }
            else if (_action == EAction.Update)
                lbAction.Text = "Thay đổi thông tin sản phẩm";
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder sb = CheckDataValidation();

            //// Lay thong tin cua san pham
            //_product.Description = fckDescription.Value;

            if (sb.Length == 0)
            {
                if (!string.IsNullOrEmpty(Daco.Web.Store.CProduct.AddProduct
                    (
                        _product.ProductID,
                        _product.ProductName,
                        _product.Series,
                        _product.Manufacture.ManufactureID,
                        _product.Manufacture.Name,
                        _product.ProductCategory.CategoryID,
                        string.Empty,
                        _product.UnitMeasure.Code,
                        _product.UnitPrice,
                        _product.EnablePriceConfidential,
                        _product.EnableShopping,
                        _product.Currency,
                        _product.UnitsInStock
                    )))
                {
                    // Add product description;
                    _product.AddDescription("Mô tả chung", fckDescription.Value);

                    // Update product photo
                    Daco.Web.Task.CUploadPhotoTask uploadPhotoTask =
                        new Daco.Web.Task.CUploadPhotoTask
                        (
                            _product.ProductID, Daco.Web.Store.EPhotoType.Product,
                            fuImage.FileUploadCollection,
                            fuImage.SelectedIndex,
                            Server.MapPath(fuImage.SaveToPath)
                        );
                    uploadPhotoTask.Run();

                    // End
                }
                else
                {
                    sb.Append(Daco.Web.Resources.Messages.InsertFailed);
                }
            }

            if (sb.Length > 0)
            {
                CMessageBox.Show(this.Page, sb.ToString());
            }
        }

        private System.Text.StringBuilder CheckDataValidation()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            _product.ProductName = Daco.Utils.CHelper.CleanHTML(tbxName.Value);
            _product.EnablePriceConfidential = chkEnablePriceConfidential.Checked;
            _product.EnableShopping = chkEnableShopping.Checked;

            if (string.IsNullOrEmpty(_product.ProductName))
                sb.AppendFormat(Daco.Web.Resources.Messages.RequiredField, "Product Name");

            if (!string.IsNullOrEmpty(tbxUnitPrice.Value))
            {
                float unitPrice = 0;
                if (!float.TryParse(tbxUnitPrice.Value, out unitPrice))
                    sb.AppendFormat(Daco.Web.Resources.Messages.InvalidNumericFormatField, "Unit Price");
                else _product.UnitPrice = unitPrice;
            }
            else _product.UnitPrice = 0;

            if (_product.EnableShopping && _product.UnitPrice < 0)
                sb.AppendFormat(Daco.Web.Resources.Messages.RequiredField, "Unit Price");

            // Series
            _product.Series = Daco.Utils.CHelper.CleanHTML(tbxSeries.Value);

            if (!string.IsNullOrEmpty(tbxUnitsInStock.Value))
            {
                int unitsInStock = 0;
                if (!int.TryParse(tbxUnitsInStock.Value, out unitsInStock))
                    sb.AppendFormat(Daco.Web.Resources.Messages.InvalidNumericFormatField, "Units in Stock");
                else _product.UnitsInStock = unitsInStock;
            }

            if (_product.EnableShopping && _product.UnitsInStock == 0)
                _product.UnitsInStock = 1;

            // Category
            if (string.IsNullOrEmpty(cboCategory.Value))
                sb.AppendFormat(Daco.Web.Resources.Messages.RequiredField, "Product Category");
            else
            {
                string categoryName = cboCategory.Items[cboCategory.SelectedIndex].Text;

                int categoryID = -1;
                if (!int.TryParse(cboCategory.Value, out categoryID))
                    categoryID = -1;
                _product.RefCategory(new Daco.Web.Store.CProductCategory(categoryID, categoryName, string.Empty));
            }
            // Manufacture
            if (string.IsNullOrEmpty(cboManufacture.Value))
                sb.AppendFormat(Daco.Web.Resources.Messages.RequiredField, "Product Manufacture");
            else
            {
                string manufactureName = cboManufacture.Items[cboManufacture.SelectedIndex].Text;

                int manufactureID = -1;
                if (!int.TryParse(cboManufacture.Value, out manufactureID))
                    manufactureID = -1;
                _product.Manufacture.ManufactureID = manufactureID;
                _product.Manufacture.Name = manufactureName;

                //_product.RefManufacture(new Daco.Web.Store.CManufacture(manufactureID, manufactureName));
            }
            // UnitMeasure code
            _product.UnitMeasure.Code = selMeasureCode.Value;
            _product.Currency = selCurrency.Items[selCurrency.SelectedIndex].Value;
            return sb;
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder sb = CheckDataValidation();
            if (sb.Length == 0)
            {
                if (_product.Update())
                {
                    // Update description
                    _product.UpdateProductDescription();

                    // Update photos
                    // Update product photo
                    Daco.Web.Task.CUploadPhotoTask uploadPhotoTask =
                        new Daco.Web.Task.CUploadPhotoTask
                        (
                            _product.ProductID, Daco.Web.Store.EPhotoType.Product,
                            fuImage.FileUploadCollection,
                            fuImage.SelectedIndex,
                            Server.MapPath(fuImage.SaveToPath)
                        );
                    uploadPhotoTask.Run();
                }
            }

            if (sb.Length > 0)
            {
                CMessageBox.Show(Page, sb.ToString());
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
        }

        private void BindForm()
        {
            if (_product != null)
            {
                tbxName.Value = _product.ProductName;
                tbxSeries.Value = _product.Series;
                tbxUnitPrice.Value = _product.UnitPrice.ToString(Config.CSiteConfig.Current.IntegerFormatString);
                tbxUnitsInStock.Value = _product.UnitsInStock.ToString(Config.CSiteConfig.Current.IntegerFormatString);

                if (_product.Manufacture.ManufactureID > 0)
                {
                    ListItem item = cboManufacture.Items.FindByValue(_product.Manufacture.ManufactureID.ToString());
                    if (item != null)
                    {
                        // Clear old selected index
                        cboManufacture.SelectedIndex = -1;
                        item.Selected = true;
                    }
                }

                if (_product.ProductCategory != null && _product.ProductCategory.CategoryID > 0)
                {
                    ListItem item = cboCategory.Items.FindByValue(_product.ProductCategory.CategoryID.ToString());
                    if (item != null)
                    {
                        // Clear old selected index
                        cboCategory.SelectedIndex = -1;
                        item.Selected = true;
                    }
                }

                if (string.IsNullOrEmpty(_product.UnitMeasure.Code))
                {
                    ListItem item = selMeasureCode.Items.FindByValue(_product.UnitMeasure.Code);
                    if (item != null)
                    {
                        selMeasureCode.SelectedIndex = -1;
                        item.Selected = true;
                    }
                }

                if (!string.IsNullOrEmpty(_product.ProductName))
                {
                    // Update mode
                    btnAddNew.Visible = false;
                    btnCancel.Visible = btnUpdate.Visible = true;
                }
                else
                {
                    btnAddNew.Visible = true;
                    btnCancel.Visible = btnUpdate.Visible = false;
                }
            }
        }
        private void BindCategoryList()
        {
            cboCategory.DataSource = GetCategoryItemList(Daco.Web.Store.CProductCategory.GetCategoryTree(-1), 0);
            cboCategory.DataBind();
        }
        private List<ListItem> GetCategoryItemList(IEnumerable<ICategory<int, CProductCategory>> categoryList, int level)
        {
            List<ListItem> itemList = new List<ListItem>();

            foreach (Daco.Web.Store.CProductCategory category in categoryList)
            {
                string str = new string(' ', level);
                itemList.Add(new ListItem(str + category.Title, category.CategoryID.ToString()));
                if (category.ChildCategories != null && category.ChildCategories.Count > 0)
                    itemList.AddRange(GetCategoryItemList(category.ChildCategories, level + 3));
            }

            return itemList;
        }
        private void BindManufactureList()
        {
            cboManufacture.Items.Clear();
            cboManufacture.DataSource = Daco.Web.Store.CProduct.GetManufactures();
            cboManufacture.DataBind();
        }
        private void BindUnitMeasureList()
        {
            selMeasureCode.Items.Clear();
            foreach (CUnitMeasure unit in CProduct.GetUnitMeasures())
                selMeasureCode.Items.Add(new ListItem(unit.Name, unit.Code));
        }
    }
}